package cn.wolfcode.mq.listener;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.domain.SeckillProduct;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
        consumerGroup = "OrderResultFailGroup",
        topic = MQConstant.ORDER_RESULT_TOPIC,
        selectorExpression = MQConstant.ORDER_RESULT_FAIL_TAG
)
public class OrderResultFailListener implements RocketMQListener<OrderMQResult> {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMQResult result) {
        System.err.println("表操作失败。。。");
        //1 同步预库存
        SeckillProduct seckillProduct = seckillProductService.queryFomDB(result.getSeckillId());
        String bigKey = SeckillRedisKey
                .SECKILL_STOCK_COUNT_HASH
                .getRealKey(result.getTime().toString());

        redisTemplate.opsForHash().put(
                bigKey,
                String.valueOf(result.getSeckillId()),
                seckillProduct.getStockCount().toString());

        //2 广播消息,本地表示设置为true
        rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,
                result.getSeckillId().toString());
    }
}
